package net.ywd.xp1024search.service;

import net.ywd.xp1024search.config.CategoryProperties;
import net.ywd.xp1024search.entity.Category;
import net.ywd.xp1024search.entity.XpPage;
import net.ywd.xp1024search.util.WebContentUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Author Dreamingodd
 * @Date 2017/4/20.
 */
@Service
public class XpSearchService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private CategoryProperties categoryProperties;

    public List<Integer> search(String selectedCategoryName, String searchText, Integer startPageNum) throws Exception {
        List<Integer> pageNums = new ArrayList<>();
        Map<String, Category> categoryMap = categoryProperties.getCategoryMap();
        Category category = null;
        for (String categoryName : categoryMap.keySet()) {
            if (categoryName.equals(selectedCategoryName)) {
                category = categoryMap.get(categoryName);
            }
        }
        if (category != null) {
            List<XpPage> xpPages = this.getSearchPages(category);
            for (int i = startPageNum; i < startPageNum + 10; i++) {
                XpPage xpPage = xpPages.get(i - 1);
                logger.debug("第" + xpPage.getPageNum() + "页");
                String webContent = WebContentUtil.readWebContent(xpPage.getUrl(), null);
                if (webContent.contains(searchText)) {
                    pageNums.add(xpPage.getPageNum());
                }
            }
        } else {
            throw new Exception("不存在这个版面！");
        }
        return pageNums;
    }

    public List<XpPage> getSearchPages(Category category) {
        List<XpPage> xpPages = new ArrayList<>();
        for (int i = 1; i <= category.getPageCount(); i++) {
            XpPage xpPage = new XpPage();
            xpPage.setCategory(category);
            xpPage.setPageNum(i);
            xpPage.setUrl(category.getLink() + i);
            xpPages.add(xpPage);
        }
        return xpPages;
    }
}
